﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using WebAppMatrix.Extensions;
using System.IO;
using System.Xml.XPath;

namespace WebAppMatrix.Configuration
{
    public class SqlConfigManager
    {
        private static string sqlFileFolder = string.Empty;
        /// <summary>
        /// Sql Xml文件放置的文件夹的绝对路径
        /// 当设置为相对路径时会根据程序目录进行转换
        /// </summary>
        public static string SqlFileFolder
        {
            get
            {
                if (sqlFileFolder.IsNullOrEmpty())
                {
                    sqlFileFolder = IOExtensions.GenerateAbsolutePath(MatrixManager.Settings.SqlFileFolder);
                }
                return sqlFileFolder;
            }
            set
            {
                sqlFileFolder = IOExtensions.GenerateAbsolutePath(value);
            }
        }

        /// <summary>
        /// 得到指定的Sql语句，注意区分大小写
        /// </summary>
        /// <param name="sentenceName">sql语句名</param>
        /// <param name="fileName">Sql Xml文件</param>
        /// <returns>sql语句，如果未找到则返回string.Empty</returns>
        public static string GetSqlSentence(string sentenceName, string fileName = null)
        {
            string sentence = string.Empty;

            if (!fileName.IsNullOrEmpty())
                sentence = getSqlSentenceFromXmlFile(sentenceName, fileName);
            else
            {
                string[] files = Directory.GetFiles(SqlFileFolder, "*.xml", SearchOption.TopDirectoryOnly);
                for (int i = 0; i < files.Count(); i++)
                {
                    sentence = getSqlSentenceFromXmlFile(sentenceName, files[i]);
                    if (!sentence.IsNullOrEmpty())
                        break;
                }
            }

            return sentence;
        }

        /// <summary>
        /// 在指定SqlFile中获取一条Sql语句，注意区分大小写。
        /// </summary>
        /// <param name="sentenceName"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static string getSqlSentenceFromXmlFile(string sentenceName, string fileName)
        {
            if (fileName.IsNullOrEmpty())
                throw new ArgumentException();
            if (Path.GetExtension(fileName).IsNullOrEmpty())
                fileName = Path.ChangeExtension(fileName, ".xml");

            string filePath = Path.Combine(SqlFileFolder, fileName);
            string xpath = "SqlFile/sentence[@name=\"" + sentenceName + "\"]";

            return Extensions.IOExtensions.GetXmlNodeValue(xpath, fileName);
        }
    }
}
